#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import time
import logging
import traceback
from datetime import datetime

# -*- coding: utf-8 -*-
from flask import render_template, url_for, redirect, request, flash, session, abort, Blueprint
from flask_cache import Cache
from werkzeug.contrib.atom import AtomFeed
from common.form import CommentForm
from models.model import Category, Post, Tag, Comment, pageby, db
# from myapp import app
from config import PER_PAGE as per_page

# cache = Cache(app, config={'CACHE_TYPE': 'simple'})

comment = Blueprint('comment', __name__, url_prefix="/comment")

log = logging.getLogger(__file__)

class PostFeed(AtomFeed):

    def add_post(self, post):
        self.add(post.post_title,
                 '',
                 content_type="html",
                 author=u'dan',
                 url=post.url,
                 updated=datetime.now(),
                 published=post.post_create_time)

# app.jinja_env.filters['html2textile'] = html2textile


def is_chinese(text):
    if text:
        for uchar in text:
            if uchar >= u'\u4e00' and uchar <= u'\u9fa5':
                return True
    return False


@comment.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


@comment.route('/error/404')
def error_404():
    return render_template('404.html'), 404

@comment.route('/addcomment', methods=['POST'])
def addcomment():
    form = CommentForm()
    error = 'Sorry, Post Comments Error!'

    if form.validate_on_submit():
        author_ip = request.environ.get('HTTP_X_FORWARDED_FOR') or '127.0.0.1'
        comment = Comment(author_ip=author_ip)
        form.populate_obj(comment)
        db.session.add(comment)
        post = Post.query.getpost_id(comment.post_id)
        post.comment_count += 1
        db.session.commit()
        return redirect(url_for('article', postid=comment.post_id))

    return render_template('/error.html', content=error)


@comment.route('/error')
def error(content='404'):
    return render_template('/error.html', content=content)












